package com.zhku.shoppingspringboot.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhku.shoppingspringboot.common.BaseContext;
import com.zhku.shoppingspringboot.common.R;
import com.zhku.shoppingspringboot.common.ResultCode;
import com.zhku.shoppingspringboot.pojo.entity.User;
import com.zhku.shoppingspringboot.pojo.vo.UserVO;
import com.zhku.shoppingspringboot.service.IUserService;
import com.zhku.shoppingspringboot.utils.FileUtils;
import com.zhku.shoppingspringboot.utils.JwtUtils;
import com.zhku.shoppingspringboot.utils.RandomStringGenerator;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jieeee
 * @since 2024-12-17
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;
    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;
    // 文件访问url
//    private final String imgUrl = "http://8.134.188.181:8090/shhopping/user/";
//    //文件保存正在服务器的文件夹
//    private final String uploadDir = "/www/server/tomcat/webapps/shopping/user/";
    private final String imgUrl = "D:\\shopping\\user";
//    //文件保存正在服务器的文件夹
    private final String uploadDir = "D:\\shopping\\user";
    @ApiOperation("用户登录接口")
    @PostMapping("/login")
    public R<UserVO> login(@RequestBody @Valid User user) {

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<User>()
                .eq(User::getAccount, user.getAccount());
        User one = userService.getOne(lambdaQueryWrapper);
//       bCryptPasswordEncoder.matches(user.getPassword(), one.getPassword()) 第一个为未加密，后面是已经加密
        if (one == null || (!bCryptPasswordEncoder.matches(user.getPassword(), one.getPassword()))) {
            return R.error(ResultCode.NO_EXIST, "账号或密码不正确");
        }
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("id", one.getId());
        BaseContext.setCurrentId(user.getId());
        String token = "Bearer "+JwtUtils.generateJwt(claims);
        UserVO userVO = BeanUtil.copyProperties(one, UserVO.class);
        userVO.setToken(token);
        log.info("id为[" + one.getId() + "]的用户登录");
        return R.success("登录成功", userVO);

    }

    @PostMapping("/regist")
    @ApiOperation("用户信息注册接口")
    public R<String> regist(@RequestBody @Valid User user) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<User>()
                .eq(User::getAccount, user.getAccount());
        User one = userService.getOne(lambdaQueryWrapper);
        if (one != null) {
            return R.error(ResultCode.HAS_EXIST, "当前账户名已经存在,请重新输入");
        }
        userService.save(user.setPassword(bCryptPasswordEncoder.encode(user.getPassword())).setUserType(0));
        return R.success("注册成功");
    }

    @PostMapping("/adminRegist")
    @ApiOperation("商家信息注册接口")
    public R<String> adminRegist(@RequestBody @Valid User user) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<User>()
                .eq(User::getAccount, user.getAccount());
        User one = userService.getOne(lambdaQueryWrapper);
        if (one != null) {
            return R.error(ResultCode.HAS_EXIST, "当前账户名已经存在,请重新输入");
        }
        userService.save(user.setPassword(bCryptPasswordEncoder.encode(user.getPassword())).setUserType(1));
        return R.success("注册成功");
    }

    @PutMapping("/setting")
    @ApiOperation("用户基本信息更改接口")
    public R<String> userSetById(@RequestBody @Valid User user) {
        if (user.getId() == null) {
            return R.error(ResultCode.VALIDATE_FAILED, "主键不能为空");
        }
        if (user.getPassword() != null && user.getPassword() != "") {
            ;
            user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        }
        userService.updateById(user);
        log.info("用户[" + BaseContext.getCurrentId() + "]更改个人信息");
        return R.success();
    }

    @PostMapping("/uploadAvatar")
    @ApiOperation("用户上传头像接口")
    public R<String> uploadProfilePicture(@RequestParam String oldPath, @RequestBody MultipartFile file) {
        String result = FileUtils.upLoadImg(uploadDir, oldPath, file);
        if (result.equals("-1")) {
            return R.error(ResultCode.VALIDATE_FAILED, "请检查文件类型");
        } else if (result.equals("-2")) {
            return R.error(ResultCode.ERROR, "服务器出错啦");
        }
        return R.success(imgUrl + result);
    }

    @GetMapping("/userList")
    public R<List<UserVO>> userList() {
        List<User> list = userService.list();
        List<UserVO> collect = list.stream().map(item -> BeanUtil.copyProperties(item, UserVO.class)).collect(Collectors.toList());
        return R.success(collect);
    }
@GetMapping("/getOne")
public R<UserVO> getOneUser(@RequestParam Integer id){
    User byId = userService.getById(id);
    if(byId!=null){
        return R.success(BeanUtil.copyProperties(byId,UserVO.class));
    }
    return R.error(ResultCode.ERROR);

}
    @DeleteMapping("/deleteUser")
    public R<String> deleteById(@RequestParam Integer id) {
        boolean b = userService.removeById(id);
        if (b) {
            return R.success("删除成功");
        }
        return R.error(ResultCode.ERROR,"删除失败");
    }

}
